package com.example.aboutspringboot.controller;

import com.example.aboutspringboot.entity.User;
import com.example.aboutspringboot.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@RequestMapping("user")
@CrossOrigin//跨域
public class UserController {

    @Resource
    private UserService userService;

    //注册
    @PostMapping("/insertOneUser")
    public Map<String,Object> insertOneUser(@RequestBody User user){
        Map<String, Object> map = new LinkedHashMap<>();
        try{
            int num=userService.insertOneUser(user);
        }catch (Exception e){
            e.printStackTrace();
            map.put("token",null);
            map.put("result",false);
            return map;
        }
        map.put("token",user.getUsername());
        map.put("result",true);
        return map;
    }
    //登录
    @PostMapping("/login")
    public Map<String,Object> login(@RequestBody User user){
        Map<String, Object> map = new LinkedHashMap<>();
        //登录
        User user1=userService.selectOneUser(user.getUsername(),user.getPassword());
        if (user1!=null){
            if (user1.getPassword().equals(user.getPassword())) {
                map.put("token", user.getUsername());
                map.put("result", true);
            }
        }else {
            map.put("token",null);
            map.put("result",false);
        }
        return map;
    }
    //按名查找用户信息
    @GetMapping("/selectOneUserByUsername")
    Map<String,Object> selectOneUserByUsername(String username){
        User user=userService.selectOneUserByUsername(username);
        Map<String, Object> map = new LinkedHashMap<>();
        if (user!=null){
            map.put("user",user);
            map.put("result",true);
        }else {
            map.put("result",false);
        }
        return map;
    }
    //充钱
    @GetMapping("/addMoney")
    Map<String,Object> addMoney(String username,double money){
        Map<String, Object> map = new LinkedHashMap<>();
        int num=userService.addMoney(username,money);
        if (num>0){
            map.put("result",true);
        }else {
            map.put("result",false);
        }
        return map;
    }
    //修改个人信息
    @PostMapping("/updateUserInfo")
    Map<String,Object> updateUserInfo(@RequestBody User user){
        Map<String, Object> map = new LinkedHashMap<>();
        int num=userService.updateOneUser(user);
        if (num>0){
            map.put("result",true);
        }else {
            map.put("result",false);
        }
        return map;
    }

}
